#include "stdafx.h"
#include "common.h"
#include "utils.h"
#include <time.h>

char    PipeBuffer[PIPE_BUFSIZE];

void WINAPI ActiveWindow(HWND hWnd){
	ShowWindow(hWnd, SW_SHOWNORMAL);
    SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
    SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
    SetForegroundWindow(hWnd);
}

CHAR* WINAPI
GetMultiString(WCHAR* str)
{
	DWORD dwNum =WideCharToMultiByte(CP_OEMCP,NULL,str,-1,NULL,0,NULL,FALSE);
	CHAR *pwText;
    pwText = new CHAR[dwNum];

	WideCharToMultiByte (CP_OEMCP,NULL,str,-1,pwText,dwNum,NULL,FALSE);
	return pwText;
}
LPWSTR WINAPI GetWideString(LPCSTR str)
{
	DWORD dwNum = MultiByteToWideChar (CP_ACP, 0, str, -1, NULL, 0);
	WCHAR *pwText;
    pwText = new WCHAR[dwNum];	
	MultiByteToWideChar (CP_ACP, 0, str, -1, pwText, dwNum);
	return pwText;
}

DWORD WINAPI HashCode(PPGate pGate,DWORD num){
	if(!pGate){
		return 0;
	}
	DWORD hash = 0;
	for(DWORD i = 0;i<num;i++){
		hash <<= 1;
		if ( hash < 0 ){
			hash |= 1;
		}
		if(pGate[i]){
			hash ^= pGate[i]->baseAddr;
		}
	}
	return hash;
}

DWORD WINAPI GetRandom(DWORD max,DWORD min){
	srand((unsigned)time(NULL));
	DWORD i = rand();
	i = i%max;
	return max(i,min);
}

DWORD WriteResponse(HANDLE hPipe,LPVOID data,DWORD cbData){
	 DWORD dwLen = 0;

	 Response resp;
	 resp.code = 0;
	 resp.cbData = cbData;

	 DWORD size = sizeof(Response) + cbData;
	 ZeroMemory(PipeBuffer,size);

	 memcpy(PipeBuffer,&resp,sizeof(Response));
	 memcpy(PipeBuffer+sizeof(Response),data,cbData);

	 WriteFile(hPipe, PipeBuffer, size, &dwLen, NULL);

	 return dwLen;
}

BOOL WINAPI ReadSomeData(PSomeData sd){
	FILE *file;
	fopen_s(&file,SOME_DATA_PATH,"rb");
	if(!file){
		LOG_DEBUG("Init fopen_s "SOME_DATA_PATH" failed!");
		return FALSE;
	}
	fread(sd, sizeof(SomeData), 1, file);
	fclose(file);
	return TRUE;
}

BOOL WINAPI WriteSomeData(PSomeData sd){
	FILE *file;
	fopen_s(&file,SOME_DATA_PATH,"wb");

	if(!file){
		LOG_DEBUG("Init fopen_s "SOME_DATA_PATH" failed!");
		return FALSE;
	}
	fwrite(sd, sizeof(SomeData), 1, file);
	fclose(file);
	return TRUE;
}